#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN MVC MODULE FOR THN WEB SERVER

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For use in commercial software, please obtain a commercial license from THN Solutions LLC.    

  + For use in free software, this library is licensed under GPL version 3. A summary of 
	GPLv3 is listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt 
	included with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 18-Apr-13 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;

using Thn;
using Thn.Text;
using Thn.Net;
using Thn.Net.Http;
#endregion

namespace Thn.Web.Mvc
{
    /// <summary>
    /// This handler is responsible for processing MVC requests.
    /// </summary>
#if DEBUG || TESTING
    public
#else
    public
#endif
 class MvcRequestHandler : IHttpRequestHandler
    {
        #region Fields
        string mDefaultControllerName = "Home";
        string mDefaultMethodName = "Index";
        #endregion

        #region Properties

        #region Controller Manager
        private IControllerManager mControllerManager;
        /// <summary>
        /// Gets or sets reference to the controller manager.
        /// </summary>
        public IControllerManager ControllerManager
        {
            get { return mControllerManager; }
            set { mControllerManager = value; }
        }
        #endregion

        #endregion

        #region IHttpRequestHandler Members

        #region Process
        /// <summary>
        /// Process an incoming request.
        /// </summary>
        /// <param name="context">The context of handling.</param>
        void IHttpRequestHandler.Process(IHttpRequestHandlingContext context)
        {
            string controllerName;
            string methodName;
            UrlQuery query;
            int idx = 0;

            #region Parse URL

            UrlParser parser = new UrlParser();
            string path = UrlEscape.Decode(context.Request.Path);
            parser.Parse(path);
            query = parser.Query;
            var parts = parser.Parts;

            #endregion

            #region Process controller name

            if (parts.Count > idx)
            {
                #region Enough parts -> extract name
                controllerName = parts[idx++];
                #endregion
            }
            else
            {
                #region Not enough parts left -> use default
                controllerName = mDefaultControllerName;
                #endregion
            }
            #endregion

            #region Process method name

            if (parts.Count > idx)
            {
                #region Enough parts -> extract name
                methodName = parts[idx++];
                #endregion
            }
            else
            {
                #region Not enough parts left -> use default
                methodName = mDefaultMethodName;
                #endregion
            }
            #endregion

            #region Execute the controller

            object result = mControllerManager.Execute(context, controllerName, methodName, query);

            #endregion

            #region Process returned result
            if (result != null)
            {
                context.IsHandled = true;

                if (result is IHttpResponse)
                {
                    #region Result is already a response -> send it directly

                    context.Response = (IHttpResponse)result;

                    #endregion
                }
                else if (result is string)
                {
                    #region Result is a string -> make a response for it

                    HttpResponse response = new HttpResponse();
                    response.Body.Writer.Write((string)result, Thn.IO.StringMode.Exact);
                    context.Response = response;

                    #endregion
                }
                else
                {
                    #region Not supported
                    throw new NotSupportedException();
                    #endregion
                }
            }
            #endregion
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public MvcRequestHandler()
            : base()
        { }
        #endregion
    }
}
